package com.wrial.seckill.error;
/*
 * @Author  Wrial
 * @Date Created in 10:32 2020/4/4
 * @Description 通用异常处理器 也可以将此类作为基类，让所有controller继承此类也可以达到效果
 */

import com.wrial.seckill.response.CommonReturnType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class CustomizeExceptionHandler {

    // 拦截自定义异常 是自定义的就返回自定义信息，否则就返回UN_KNOW_ERROR  每次做完一个东西后都要对其代码优化
    @ExceptionHandler(Exception.class)
    @ResponseBody
    Object handle(Throwable ex) {
        CommonReturnType returnType;
        Map<String, Object> map = new HashMap<>();
        if (ex instanceof CustomizeException) {
            CustomizeException exception = (CustomizeException) ex;
            map.put("errCode", exception.getCode());
            map.put("errMsg", exception.getMessage());
        } else {
            map.put("errCode", CustomizeErrorCode.UNKNOWN_ERROR.getCode());
            map.put("errMsg", CustomizeErrorCode.UNKNOWN_ERROR.getMessage());
        }
        returnType = CommonReturnType.create(map, "fail");
        return returnType;
    }


}
